//
//  CalssifyViewController.m
//  MyNewProject
//
//  Created by 王春辉 on 12/9/19.
//  Copyright © 2019 sun. All rights reserved.
//

#import "CalssifyViewController.h"
#import "AuctionNewUserEnjoyView.h"
#import "ClassifyTableViewDelegate.h"
#import "ClassifyCollectionViewDelegate.h"
#import "ClassifySectionVC.h"
#import "SearchResultVC.h"
#import "AuctionCouponVC.h"
#import "ProductDetailVC.h"

#pragma mark -- mark Model
#import "HomeShopModel.h"
#import "AuctionHomeModel.h"

@interface CalssifyViewController () {
    
}
@property (nonatomic, strong) UIButton *searchBtn;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIImageView *rightHeaderViewView;


@property (nonatomic, strong) AuctionNewUserEnjoyView *couponView;
@property (nonatomic, strong) ClassifyTableViewDelegate *tableViewDelegate;
@property (nonatomic, strong) ClassifyCollectionViewDelegate *collectionViewDelegate;


@property (nonatomic, copy) ClassifyTableViewDidSelectRowAtIndexPathBlock tableViewBlock;
@property (nonatomic, copy) ClassifyCollectionViewScrollToRowAtIndexPathBlock collectionViewBlock;
@property (nonatomic, copy) ClassifyCollectionViewDidSelectItemAtIndexPathBlock collectionSelectBlock;
@property (nonatomic, copy) void(^CouponButtonClickBlock)(void);

#pragma mark -- mark 数据相关
@property (nonatomic, strong) NSArray <HomeShopClassifyModel *>*dataArray;
@property (nonatomic, strong) AuctionHomeDataModel *productDataModel;
@end

@implementation CalssifyViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestContentData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"商城";
    [self initBlock]; // 初始化block
//    [self addRightItemBarButton]; // 添加右导航栏按钮
    [self setUpContentView];
}
/// 右侧导航栏按钮
- (void)addRightItemBarButton {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"shop_share_bar_btn_img"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(shareBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [self setGk_navRightBarButtonItem:barButton];
}

/// contentView
- (void)setUpContentView {
    [self hideNavLine];
    
    UIView *h_line = [[UIView alloc] initWithFrame:CGRectZero]; // 横向分割线
    h_line.backgroundColor = SKColorWithHex(0xE5E5E5);
    [self.view addSubview:h_line];
    
    UIView *v_line = [[UIView alloc] initWithFrame:CGRectZero]; // 纵向分割线
    v_line.backgroundColor = SKColorWithHex(0xE5E5E5);
    [self.view addSubview:v_line];
    
    [self.couponView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(self.couponView.mas_width).multipliedBy(187.0/345);
        make.top.mas_offset(GK_STATUSBAR_NAVBAR_HEIGHT);
    }];
    
    [self.searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(self.searchBtn.mas_width).multipliedBy(42.0/345);
        make.top.mas_equalTo(self.couponView.mas_bottom).mas_offset(10);
    }];
    
    [h_line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.height.mas_equalTo(0.4);
        make.top.mas_equalTo(self.searchBtn.mas_bottom).mas_offset(10.5);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.top.mas_equalTo(h_line.mas_bottom);
        make.bottom.mas_offset(0);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(100.0/375.0);
    }];
    
    [v_line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.tableView.mas_right);
        make.top.bottom.mas_equalTo(self.tableView);
        make.width.mas_equalTo(h_line.mas_height);
    }];
    
    [self.rightHeaderViewView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(v_line.mas_right).mas_offset(17);
        make.top.mas_equalTo(v_line).mas_offset(14);
        make.right.mas_offset(-12.5);
        make.height.mas_equalTo(self.rightHeaderViewView.mas_width).multipliedBy(71.0/245.0);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.rightHeaderViewView);
        make.bottom.mas_offset(0);
        make.top.mas_equalTo(self.rightHeaderViewView.mas_bottom).mas_offset(14);
    }];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestContentData)];
    [self.couponView setCouponUseButtonClickBlock:self.CouponButtonClickBlock];
}

#pragma mark -- mark 懒加载
- (UIButton *)searchBtn {
    if (!_searchBtn) {
        self.searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_searchBtn addTarget:self action:@selector(searchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_searchBtn];
        [_searchBtn setImage:[UIImage imageNamed:@"shop_search_btn_img"] forState:UIControlStateNormal];
        _searchBtn.layer.masksToBounds = true;
        _searchBtn.layer.cornerRadius = 4.0f;
        _searchBtn.backgroundColor = SKColorWithHex(0xF2F2F2);
        [_searchBtn setTitle:@"请输入商品名称和分类" forState:UIControlStateNormal];
        _searchBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _searchBtn.imageEdgeInsets = UIEdgeInsetsMake(_searchBtn.imageEdgeInsets.top, 15, _searchBtn.imageEdgeInsets.bottom, _searchBtn.imageEdgeInsets.right - 15);
        _searchBtn.titleEdgeInsets = UIEdgeInsetsMake(_searchBtn.titleEdgeInsets.top, _searchBtn.titleEdgeInsets.left + 15, _searchBtn.titleEdgeInsets.bottom, _searchBtn.titleEdgeInsets.right - 15);
        [_searchBtn setTitleColor:SKColorWithHex(0xB1B1B1) forState:UIControlStateNormal];
        _searchBtn.titleLabel.font = SKFONT_SIZE(16);
    }
    return _searchBtn;
}
- (AuctionNewUserEnjoyView *)couponView {
    if (!_couponView) {
        _couponView = [[AuctionNewUserEnjoyView alloc] init];
        _couponView.backgroundColor = [UIColor lightGrayColor];
        [self.view addSubview:_couponView];
    }
    return _couponView;
}
- (UITableView *)tableView {
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.showsVerticalScrollIndicator = false;
        _tableView.showsHorizontalScrollIndicator = false;
        _tableView.delegate = self.tableViewDelegate;
        _tableView.dataSource = self.tableViewDelegate;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
        _tableView.tableFooterView = [UIView new];
        [_tableView registerClass:[ClassifyTableViewCell class] forCellReuseIdentifier:@"tableView_cell_identifier"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 20;
        layout.minimumInteritemSpacing = 25;
        layout.sectionInset = UIEdgeInsetsMake(17.5, 12, 17.7, 12);
        CGFloat collectionView_w = self.view.width * 275.0 / 375.0 - 17 - 12.5;
        CGFloat w = (collectionView_w - 12 - 12 - 17.5 * 4) / 3;
        CGFloat h = w + 10 + 13;
        layout.itemSize = CGSizeMake(w, h);
        layout.headerReferenceSize = CGSizeMake(_collectionView.width, 13);
        layout.footerReferenceSize = CGSizeZero;
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.showsVerticalScrollIndicator = false;
        _collectionView.showsHorizontalScrollIndicator = false;
        _collectionView.delegate = self.collectionViewDelegate;
        _collectionView.dataSource = self.collectionViewDelegate;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[ClassifyCollectionViewCell class] forCellWithReuseIdentifier:@"collection_cell_identifier"];
        [_collectionView registerClass:[ClassifyCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collection_header_identifier"];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
- (UIImageView *)rightHeaderViewView {
    if (!_rightHeaderViewView) {
        self.rightHeaderViewView = [[UIImageView alloc] initWithFrame:CGRectZero];
        _rightHeaderViewView.backgroundColor = [UIColor whiteColor];
        _rightHeaderViewView.contentMode = UIViewContentModeScaleAspectFill;
        _rightHeaderViewView.layer.cornerRadius = 4.0;
        _rightHeaderViewView.layer.masksToBounds = true;
        _rightHeaderViewView.backgroundColor = [UIColor lightGrayColor];
        _rightHeaderViewView.image = SKIMAGE_NAMED(@"auction_classify_banner_img");
        [self.view addSubview:_rightHeaderViewView];
    }
    return _rightHeaderViewView;
}
- (ClassifyTableViewDelegate *)tableViewDelegate {
    if (!_tableViewDelegate) {
        self.tableViewDelegate = [[ClassifyTableViewDelegate alloc] init];
        [_tableViewDelegate didSelectRowAtIndexPathBlock:self.tableViewBlock];
    }
    return _tableViewDelegate;
}
- (ClassifyCollectionViewDelegate *)collectionViewDelegate {
    if (!_collectionViewDelegate) {
        self.collectionViewDelegate = [[ClassifyCollectionViewDelegate alloc] init];
        _collectionViewDelegate.respondScrll = true;
        [_collectionViewDelegate scrollViewToRowAtIndexPathBlock:self.collectionViewBlock];
        [_collectionViewDelegate didSelectItemAtIndexPathBlock:self.collectionSelectBlock];
    }
    return _collectionViewDelegate;
}


#pragma mark -- mark 网络请求

/**
 获取网络数据
 */
- (void)requestContentData {
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Shop/getShopType" params:@{} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        HomeShopModel *model = [HomeShopModel modelWithDictionary:response];
        if ([model isSuccess]) {
            weakSelf.dataArray = model.data;
            [weakSelf reloadData];
        }else {
            [weakSelf showMessage:model.msg];
        }
        if ([weakSelf.collectionView.mj_header isRefreshing]) {
            [weakSelf.collectionView.mj_header endRefreshing];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
        if ([weakSelf.collectionView.mj_header isRefreshing]) {
            [weakSelf.collectionView.mj_header endRefreshing];
        }
    }];
    [self requestNewUserCouponData];
}

/// 新人专享
- (void)requestNewUserCouponData {
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Shop/getNewGoods" params:@{} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        AuctionHomeModel *model = [AuctionHomeModel modelWithDictionary:response];
        if ([model isSuccess]) {
            [weakSelf reloadAuctionViewWith:model];
        }else {
            [weakSelf reloadAuctionViewWith:model];
        }
    } failBlock:^(NSError *error) {
        
    }];
}

#pragma mark -- mark EVENT

/// 点击搜索按钮
/// @param sender sender
- (void)searchButtonClick:(UIButton *)sender {
    // 跳转搜索界面
    SearchResultVC *vc = [[SearchResultVC alloc] init];
    [self.navigationController pushViewController:vc animated:true];
}

/**
 shareBarButtonItemClick

 @param sender item
 */
- (void)shareBarButtonClick:(UIButton *)sender {
    // 分享
    
}

#pragma mark -- mark 业务逻辑
- (void)initBlock {
    __weak typeof(self) weakself = self;
    self.tableViewBlock = ^(NSIndexPath *indexPath) {
        if (indexPath.row == 0 && self.collectionView.contentOffset.y == 0) {
            return ;    }
        weakself.collectionViewDelegate.respondScrll = false;
        NSIndexPath *collectionIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        // 限制一下
        HomeShopClassifyModel *model = weakself.dataArray[collectionIndexPath.section];
        if (model.goods_type_two.count > 0) {
            [weakself.collectionView scrollToItemAtIndexPath:collectionIndexPath atScrollPosition:UICollectionViewScrollPositionTop animated:true];
        }
    };
    self.collectionViewBlock = ^(NSIndexPath *indexPath) {
        NSIndexPath *tableViewIndexPath = [NSIndexPath indexPathForRow:indexPath.section inSection:0];
        if (weakself.dataArray.count > 0) {
            [weakself.tableView selectRowAtIndexPath:tableViewIndexPath animated:true scrollPosition:UITableViewScrollPositionTop];
        }
    };
    SKWeakSelf;
    self.collectionSelectBlock = ^(NSIndexPath *indexPath) {
        // collection点击事件回调
        HomeShopClassifyModel *model = weakSelf.dataArray[indexPath.section];
        HomeShopClassifySectionModel *sectionModel = model.goods_type_two[indexPath.item];
        ClassifySectionVC *vc = [[ClassifySectionVC alloc] init];
        vc.gk_navTitle = sectionModel.name;
        vc.typeId = sectionModel.Id;
        [weakSelf.navigationController pushViewController:vc animated:true];
    };
    // 优惠券
    self.CouponButtonClickBlock = ^{
        if ([[UserInfoSingleton shareInstance].userInfo isLogin]) {
            // 优惠券
            AuctionCouponVC *vc = [[AuctionCouponVC alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:true];
        }else {
            [AppDelegate pushLoginView];
        }
    };
    self.couponView.couponProductButtonClickBlock = ^(NSInteger index) {
        if (weakSelf.productDataModel) {
            NSArray <ProductDetailModel *>* goods = weakSelf.productDataModel.goods;
            ProductDetailModel *ptModel1 = goods[index];
            ProductDetailVC *vc = [[ProductDetailVC alloc] init];
            vc.type = 0;
            vc.ptId = ptModel1.ptId;
            vc.showType = ProductDetailTypeDetail;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
}


/**
 刷新数据
 */
- (void)reloadData {
    NSMutableArray <NSString *>*titles = [NSMutableArray arrayWithCapacity:self.dataArray.count];
    [self.dataArray enumerateObjectsUsingBlock:^(HomeShopClassifyModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [titles addObject:obj.title];
    }];
    self.tableViewDelegate.dataArray = titles;
    [self.tableView reloadData];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:true scrollPosition:UITableViewScrollPositionTop];
    
    self.collectionViewDelegate.dataArray = self.dataArray;
    [self.collectionView reloadData];
}

/**
 刷新数据

 @param model model
 */
- (void)reloadAuctionViewWith:(AuctionHomeModel *)model {
    self.couponView.dataModel = model;
    [self.couponView layoutSubviews];
    self.productDataModel = model.data;
}
@end

